package com.biglead.demo.rabbit.order.common;


import com.biglead.demo.pojo.SecKillMessage;
import com.biglead.demo.pojo.SeckillGoods;
import com.biglead.demo.pojo.SeckillOrder;
import com.biglead.demo.service.OrderService;
import com.biglead.demo.service.SecKillGoodsService;
import com.biglead.demo.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OrderMQReceiver {

    @Autowired
    private SecKillGoodsService secKillGoodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = "seckillQueue")
    public void receiveSecKillMessage(String message) {
        log.info("接收的秒杀订单消息：{}", message);
        SecKillMessage secKillMessage = JsonUtils.toObj(message, SecKillMessage.class);

        Long userId = secKillMessage.getUserId();
        Long goodsId = secKillMessage.getGoodsId();
        Long sn = secKillMessage.getSn();
        //查询秒杀商品
        SeckillGoods seckillGoods = secKillGoodsService.findByGoodsId(goodsId);
        // 库存不足
        if (seckillGoods.getStockCount() < 1) {
            //更新redis订单状态
            redisTemplate.opsForValue().set("sn:" + sn, "秒杀失败 库存不足",1, TimeUnit.DAYS);
            log.error("库存不足");
            return;
        }

        // 判断是否重复抢购
        // 重复抢购
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + userId + ":" + goodsId);
        if (!Objects.isNull(seckillOrder)) {
            //更新redis订单状态
            redisTemplate.opsForValue().set("sn:" + sn, "秒杀失败 重复抢购",1, TimeUnit.DAYS);
            log.error("重复抢购 userId:{} goodsId:{}",userId,goodsId);
            return;
        }

        // 下订单
        orderService.toSecKill(goodsId, userId,sn);
    }

    @RabbitListener(queues = "commonOrderQueue")
    public void receiveCommonOrderMessage(String message) {
        log.info("接收的普通订单消息：{}", message);
        SecKillMessage secKillMessage = JsonUtils.toObj(message, SecKillMessage.class);
        Long userId = secKillMessage.getUserId();
        Long goodsId = secKillMessage.getGoodsId();
        Long sn = secKillMessage.getSn();
        orderService.createOrder(goodsId, userId,sn);
    }

}
